package vek.GUI.Infoview;

import java.io.IOException;
import java.util.Timer;


/**
 * This class is responsible for loading the website.
 * Runs as a thread and uses WebsiteLoaderChecker to stop loading the website in case too long time has passed
 * @author Christian, Michal og Jakob (Hold 1, gruppe 2)
 */
public class WebsiteLoader extends Thread{
    
    private boolean shouldRun = true;
    private boolean hasNotRunOnce = true;
    private String urlToPage;
    private WebsiteViewer websiteViewer;
    
    public WebsiteLoader(WebsiteViewer wv)
    {
        websiteViewer = wv;
    }
    
    /**
     * Loads the webisite
     * @param url the url of the website to be loaded
     */
    
    public void loadPage(String url)
    {
        urlToPage = url;
        start();
        
    }
    
    /**
     * Terminates this thread.
     * 
     * NOTE: this does not forcibly terminate the thread as this is discouraged by SUN, thus the thread is not guranteed to terminate.
     */
    
    public void stopThread()
    {
        shouldRun = false;
        
        interrupt();
    }
    
    /**
     * Tries to load the website.
     */
    
    public void run()
    {
        while(shouldRun && hasNotRunOnce) // alternative to forcibly stopping this thread as it is discouraged by Sun (see Thread)
        {
        if(websiteViewer != null && urlToPage != null && urlToPage.length() != 0)
        {
            startTimer();
            try { websiteViewer.setPage(urlToPage); }
            catch (Exception e) 
            {
                
                try
                {
                    //nothing, can be used for backup webpage 
                }
                catch (Exception e2) 
                {
                   websiteViewer.setContentType("plain text");
                        
                }
                System.err.println("error in Website Loader"); 
            }
            hasNotRunOnce = false;
        
        }
        }
    }
    
    /**
     * Makes sure that the website loading is stopped using WebsiteLoaderChecker. This is to prevent the program from continuing to load the webiste even though it can't be loadede.
     */
    
    private void startTimer() 
    {
        Timer timer = new Timer();
        WebsiteLoaderChecker timertask = new WebsiteLoaderChecker(this);

        timer.schedule(timertask, 5000);
    }

}
